package ooo.reindeer.concurrent.coder;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import ooo.reindeer.concurrent.ICoder;

import java.io.IOException;

public class JsonCoder<T> implements ICoder<T, byte[]> {
    ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public T decode(byte[] bytes) {
        try {
            return (T) (objectMapper.readValue(bytes, Transport.class).getData());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public byte[] encode(T a) {
        try {
            return objectMapper.writeValueAsBytes(new Transport(a));
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }


    class Transport<T> {

        @JsonCreator
        public Transport(@JsonProperty("data") T data) {
            this.data = data;
        }

        public T getData() {
            return data;
        }

        public void setData(T data) {
            this.data = data;
        }

        @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, property = "@C")
        T data;
    }
}
